package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.BasePresenter
import com.yl.ydk.bean.SiteAricleBean
import com.yl.ydk.presenter.contract.SiteArticleActivityContract
import com.yl.ydk.ui.activity.SiteAricleDetailActivity
import com.yl.ydk.ui.adapter.SiteAricleAdapter
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class SiteArticleActivityImpl : BasePresenter<SiteArticleActivityContract.View>(),
    SiteArticleActivityContract.Presenter<SiteArticleActivityContract.View> {

    override fun getSiteAricle(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getSiteAricle(*query)
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<SiteAricleBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: SiteAricleBean?) {
                        dismissLoadingDialog()
                        if (t?.data!= null && t.code == 200) {
                            mView?.getRecyclerView()?.let {
                                val adapter = SiteAricleAdapter(t.data.list.toMutableList())
                                val manager = LinearLayoutManager(context)
                                it.adapter = adapter
                                it.layoutManager = manager
                                adapter.onListItemClick(object : SiteAricleAdapter.onListItemClick {
                                    override fun onListItemClick(item: SiteAricleBean.DataX?) {
                                        mView?.getActivity()?.let {
                                            val intent = Intent(it, SiteAricleDetailActivity::class.java)
                                            intent.putExtra("data", item?.id.toString())
                                            it.startActivityIn(intent, it)
                                        }
                                    }
                                })
                            }
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }


}